<template>
    <div>
      <!-- 工具栏 -->
      <div>
        <el-row>
          <el-col :span="8">
            <!-- 操作按钮 -->
            <div class="operation-div">
              <el-button type="primary" @click="onAdd">添加</el-button>
            </div>
          </el-col>
          <el-col :span="16">
            <!-- 条件查询 -->
            <div class="search-div">
              <el-form :inline="true" :model="searchData" class="demo-form-inline">
                <el-form-item label="地区名称：">
                  <el-input v-model="searchData.regionName" placeholder="请输入地区名称" clearable />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSearch">查询</el-button>
                  <el-button type="primary" @click="onReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 表格内容 -->
      <div>
        <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="{ background: '#ECF5FF' }">
          <el-table-column type="index" :index="indexMethod" />
          <el-table-column prop="regionName" label="地区名称" />
          <el-table-column prop="createdAt" label="创建时间" />
          <el-table-column prop="updatedAt" label="更新时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin-top: 20px">
          <el-pagination
            v-model:current-page="pageData.currentPage"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            background
            layout="->, jumper, total, sizes, prev, pager, next"
            :total="pageData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  
    <!-- 添加修改对话框表单-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" draggable overflow @close="onDialogFormCancel">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item label="地区名称" prop="regionName">
          <el-input v-model="form.regionName" :disabled="!isAdd" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onDialogFormCancel">取消</el-button>
          <el-button type="primary" @click="onDialogFormConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue';
  import { addRegionService, getRegionById, updateRegionService, deleteByIdRegionService, pageListRegionService } from '@/api/region.js';
  import { ElMessage, ElMessageBox } from 'element-plus';
  
  // 表单数据
  const searchData = ref({
    regionName: '',
  });
  // 表格数据
  const tableData = ref([]);
  
  /** 分页 */
  // 分页数据
  const pageData = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 20,
  });
  // 分页插件，每页条数发生改变时
  const handleSizeChange = (val) => {
    pageData.pageSize = val;
    getPageList();
  };
  // 分页插件，当页码发生改变时
  const handleCurrentChange = (val) => {
    pageData.currentPage = val;
    getPageList();
  };
  
  // 分页查询
  const getPageList = async () => {
    const params = {
      currentPage: pageData.currentPage,
      pageSize: pageData.pageSize,
      regionName: searchData.value.regionName,
    };
    const result = await pageListRegionService(params);
    pageData.total = result.data.total;
    tableData.value = result.data.items;
  };
  getPageList();
  
  // 头部表单函数定义
  const onSearch = () => {
    getPageList();
  };
  // 重置查询表单
  const onReset = () => {
    searchData.value = {};
    getPageList();
  };
  
  /** 添加修改对话框表单 */
  const form = ref({
    regionName: ''
  });
  // 重置对话框表单
  const resetForm = () => {
    form.value = {
      regionName: ''
    };
    title.value = '添加地区';
    isAdd.value = true;
  };
  const title = ref('添加地区');
  const isAdd = ref(true);
  const dialogFormVisible = ref(false);
  
  // 提交对话框表单按钮事件
  const onDialogFormConfirm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        confirm();
      }
    });
  };
  // 取消对话表单框按钮事件
  const onDialogFormCancel = () => {
    dialogFormVisible.value = false;
    resetForm();
  };
  
  // 添加按钮事件
  const onAdd = () => {
    title.value = '添加地区';
    isAdd.value = true;
    dialogFormVisible.value = true;
  };
  
  // 修改按钮事件
  const handleEdit = async (index, row) => {
    title.value = '修改地区';
    isAdd.value = false;
    const id = { id: row.regionId };
    let result = await getRegionById(id);
    form.value = result.data;
    dialogFormVisible.value = true;
  };
  
  // 删除按钮事件
  const handleDelete = (index, row) => {
    ElMessageBox.confirm('确认要删除吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let result = await deleteByIdRegionService(row.regionId);
        ElMessage.success(result.msg ? result.msg : '删除成功');
        getPageList();
      })
      .catch(() => {});
  };
  
  // 提交表单
  const confirm = async () => {
    if (isAdd.value) {
      try {
        let result = await addRegionService(form.value);
        ElMessage.success(result.msg ? result.msg : '添加成功');
        dialogFormVisible.value = false;
        resetForm();
        getPageList();
      } catch (error) {}
    } else {
      try {
        let result = await updateRegionService(form.value);
        ElMessage.success(result.msg ? result.msg : '修改成功');
        dialogFormVisible.value = false;
        resetForm();
        getPageList();
      } catch (error) {}
    }
  };
  
  /** 表单校验 */
  const ruleFormRef = ref(null);
  const rules = ref({
    regionName: [{ required: true, message: '请输入地区名称', trigger: 'blur' }]
  });
  </script>
  
  <style scoped>
  .operation-div {
    width: 100%;
    text-align: left;
    padding-left: 10px;
    padding-top: 10px;
  }
  
  .search-div {
    width: 100%;
    text-align: right;
    padding-top: 10px;
  }
  </style>
  